<template>
  <!-- 添加商品页面 -->
  <div class="Bread">
  <Bread></Bread>
  </div>
  
  <div class="addgoods">
    <div>
      <el-steps :active="active" align-center finish-status="success">
        <el-step title="填写商品信息" />
        <el-step title="填写商品促销" />
        <el-step title="填写商品属性" />
        <el-step title="选择商品关联" />
      </el-steps>
    </div>
    <!-- 填写商品信息 -->
    <div v-show="active === 0">
      <el-form label-width="120px" :model="ruleForm" :rules="rules" ref="ruleFormRef">
        <el-form-item label="商品分类：" prop="productCategoryId">
          <el-cascader
            :options="withChildrenList"
            clearable
            v-model="ruleForm.productCategoryId"
          />
        </el-form-item>
        <el-form-item label="商品名称：" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="副标题：" prop="subTitle">
          <el-input v-model="ruleForm.subTitle" />
        </el-form-item>
        <el-form-item label="商品品牌：" prop="brandName">
          <el-select
            v-model="ruleForm.brandName"
            class="m-2"
            placeholder="请选择品牌"
            size="large"
          >
            <el-option
              v-for="item in categoryData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品介绍：">
          <el-input v-model="ruleForm.desc" type="textarea" />
        </el-form-item>
        <el-form-item label="商品货号：">
          <el-input v-model="ruleForm.num" />
        </el-form-item>
        <el-form-item label="商品售价：">
          <el-input v-model="ruleForm.price" />
        </el-form-item>
        <el-form-item label="市场价：">
          <el-input v-model="ruleForm.rmb" />
        </el-form-item>
        <el-form-item label="商品库存：">
          <el-input v-model="ruleForm.stock" />
        </el-form-item>
        <el-form-item label="计量单位：">
          <el-input v-model="ruleForm.unit" />
        </el-form-item>
        <el-form-item label="商品重量：">
          <el-input
            v-model="ruleForm.weight"
            size="small"
            style="width: 200px"
          />&nbsp;&nbsp;&nbsp;克
        </el-form-item>
        <el-form-item label="排序:">
          <el-input v-model="ruleForm.sort" />
        </el-form-item>
      </el-form>
    </div>
    <!-- 商品促销 -->
    <div v-show="active === 1">
      <el-form :model="ruleForm" label-width="120px" ref="ruleFormRef">
        <el-form-item label="赠送积分:">
          <el-input v-model="ruleForm.integral" />
        </el-form-item>
        <el-form-item label="赠送成长值:">
          <el-input v-model="ruleForm.value" />
        </el-form-item>
        <el-form-item label="积分购买限制:">
          <el-input v-model="ruleForm.limits" />
        </el-form-item>
        <el-form-item label="预告商品:">
          <el-switch v-model="ruleForm.foreshow" />
        </el-form-item>
        <el-form-item label="商品上架:">
          <el-switch v-model="ruleForm.sale" />
        </el-form-item>
        <el-form-item label="商品推荐:">
          <el-switch v-model="ruleForm.newStatus" inactive-text="新品" />
          <el-switch v-model="ruleForm.recommend" inactive-text="推荐" />
        </el-form-item>
        <el-form-item label="服务保证:" prop="promise">
          <el-checkbox v-model="ruleForm.return">无忧退货</el-checkbox>
          <el-checkbox v-model="ruleForm.fast">快速退款</el-checkbox>
          <el-checkbox v-model="ruleForm.free">免费包邮</el-checkbox>
        </el-form-item>
        <el-form-item label="详细页标题:">
          <el-input v-model="ruleForm.detailTitle" />
        </el-form-item>
        <el-form-item label="详细页描述：">
          <el-input v-model="ruleForm.detailDesc" />
        </el-form-item>
        <el-form-item label="商品关键字:">
          <el-input v-model="ruleForm.keywords" />
        </el-form-item>
        <el-form-item label="商品备注:">
          <el-input v-model="ruleForm.notes" />
        </el-form-item>
        <el-form-item label="选择优惠方式:">
          <div class="demo-button-style">
            <el-checkbox-group v-model="checkboxGroup4" size="small">
              <el-checkbox-button
                v-for="discountWay in discountWays"
                :key="discountWay"
                :label="discountWay"
                >{{ discountWay }}</el-checkbox-button
              >
            </el-checkbox-group>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <!-- 商品属性 -->
    <div v-show="active === 2">
      <el-form label-width="120px" ref="ruleFormRef">
        <!-- 1 -->
        <el-form-item label="属性类型:">
          <el-select v-model="ruleForm.brandId" placeholder="请选择属性类型">
            <el-option
              v-for="item in optionsB1"
              :key="item.id"
              :label="item.value"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- 2 -->
        <el-form-item label="商品规格:">
          <div class="gray"></div>
          <el-table border style="width: 100%; margin-top: 20px; margin-bottom: 20px">
            <el-table-column label="销售价格" />
            <el-table-column label="商品库存" />
            <el-table-column label="库存预警值" />
            <el-table-column label="SKU编号" />
            <el-table-column label="操作" />
          </el-table>
          <el-button type="primary" @click="refresh"> 刷新列表 </el-button>
          <el-button type="primary" @click="syncPrice"> 同步价格 </el-button>
          <el-button type="primary" @click="syncStock"> 同步库存 </el-button>
        </el-form-item>
        <!-- 3 -->
        <el-form-item label="商品参数:">
          <div class="gray"></div>
        </el-form-item>
        <!-- 4 -->
        <el-form-item label="商品相册:">
          <el-upload
            class="upload-demo"
            :action="action"
            :on-success="handlesuccess"
            list-type="picture"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <!-- 5 -->
        <el-form-item label="规格参数:">
          <el-tabs type="border-card">
            <el-tab-pane label="电脑端详情"></el-tab-pane>
            <el-tab-pane label="移动端详情"></el-tab-pane>
            <!-- 富文本 -->
            <vue-quill-text-editor ref="quillRef" />
          </el-tabs>
        </el-form-item>
      </el-form>
    </div>
    <!-- 商品关联 -->
    <div v-show="active === 3">
      <el-form label-width="120px" ref="ruleFormRef">
        <p style="text-align: center; margin: 0 0 20px"></p>
        <div style="text-align: center">
          <!-- 1 -->
          <el-form-item label="关联专题:">
            <el-transfer
              v-model="rightValue"
              style="text-align: left; display: inline-block"
              filterable
              filter-placeholder="请输入专题名称"
              :left-default-checked="['']"
              :right-default-checked="[]"
              :titles="['待选择', '已选择']"
              :button-texts="['', '']"
              :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}',
              }"
              :data="data1"
            >
            </el-transfer>
          </el-form-item>
          <!-- 2 -->
          <p style="text-align: center; margin: 50px 0 20px"></p>
          <el-form-item label="关联优选:">
            <div style="text-align: center">
              <el-transfer
                v-model="leftValue"
                style="text-align: left; display: inline-block"
                filter-placeholder="请输入优选名称"
                filterable
                :left-default-checked="[]"
                :right-default-checked="[]"
                :titles="['待选择', '已选择']"
                :button-texts="['', '']"
                :format="{
                  noChecked: '${total}',
                  hasChecked: '${checked}/${total}',
                }"
                :data="data2"
              >
                <template #default="{ option }">
                  <span>{{ option.label }}</span>
                </template>
              </el-transfer>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- 按钮 -->
    <div class="btns">
      <el-button @click="prev" v-if="active === 1">上一步,填写商品信息</el-button>
      <el-button type="primary" @click="next" v-if="active === 0"
        >下一步,填写商品促销</el-button
      >
      <el-button @click="prev" v-if="active === 2">上一步,填写商品促销</el-button>
      <el-button type="primary" @click="next" v-if="active === 1"
        >下一步,填写商品属性</el-button
      >
      <el-button @click="prev" v-if="active === 3">上一步,填写商品属性</el-button>
      <el-button type="primary" @click="next" v-if="active === 2"
        >下一步,选择商品关联</el-button
      >
      <el-button type="primary" @click="submit(ruleFormRef)" v-if="active === 3"
        >完成,提交商品</el-button
      >
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { ref, watch } from "vue";
import * as api from "@/request/api";
import type { IBrandListItem } from "@/request/PmsAdminConreiller/index";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps, UploadUserFile } from "element-plus";
import Bread from "@/components/Bread.vue";
//表单效验规则
// 校验每一项
const ruleForm = reactive({
  albumPics: "",
  brandId: "",
  brandName: "",
  deleteStatus: 0,
  description: "",
  detailDesc: "",
  detailHtml: "",
  detailMobileHtml: "",
  detailTitle: "",
  feightTemplateId: 0,
  flashPromotionCount: 0,
  flashPromotionId: 0,
  flashPromotionPrice: 0,
  flashPromotionSort: 0,
  giftPoint: 0,
  giftGrowth: 0,
  keywords: "",
  lowStock: 0,
  name: "",
  newStatus: 0,
  note: "",
  originalPrice: 0,
  pic: "",
  memberPriceList: [
    {
      memberLevelId: 1,
      memberLevelName: "黄金会员",
    },
    {
      memberLevelId: 2,
      memberLevelName: "白金会员",
    },
    {
      memberLevelId: 3,
      memberLevelName: "钻石会员",
    },
  ],
  productFullReductionList: [
    {
      fullPrice: 0,
      reducePrice: 0,
    },
  ],
  productLadderList: [
    {
      count: 0,
      discount: 0,
      price: 0,
    },
  ],
  previewStatus: 0,
  price: "",
  productAttributeCategoryId: null,
  productAttributeValueList: [],
  skuStockList: [],
  subjectProductRelationList: [],
  prefrenceAreaProductRelationList: [],
  productCategoryId: "",
  productCategoryName: "11111",
  productSn: "",
  promotionEndTime: "",
  promotionPerLimit: 0,
  promotionPrice: null,
  promotionStartTime: "",
  promotionType: 0,
  publishStatus: 0,
  recommandStatus: 0,
  sale: 0,
  serviceIds: "",
  sort: 0,
  stock: "",
  subTitle: "",
  unit: "",
  usePointLimit: 0,
  verifyStatus: 0,
  weight: "",
});
const rules = reactive<FormRules>({
  //商品分类
  productCategoryId: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
    },
  ],
  //商品名称
  name: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { min: 2, max: 140, message: "长度在 2 到 140 个字符", trigger: "blur" },
  ],
  //副标题
  subTitle: [{ required: true, message: "请输入商品副标题", trigger: "blur" }],
  //商品品牌
  brandName: [{ required: true, message: "请选择商品品牌", trigger: "change" }],
});
//表单数据
const ruleFormRef = ref<FormInstance>();
//选择商品关联
interface Option {
  key: number;
  label: string;
  initial: string;
}

// 步骤2 选择优惠方式
const checkboxGroup4 = ref(["无优惠"]);
const discountWays = ["无优惠", "特惠促销", "会员价格", "阶梯价格", "满减价格"];

//
const generateData = () => {
  const data: Option[] = [];
  const states = [
    "California",
    "Illinois",
    "Maryland",
    "Texas",
    "Florida",
    "Colorado",
    "Connecticut ",
  ];
  const initials = ["CA", "IL", "MD", "TX", "FL", "CO", "CT"];
  states.forEach((city, index) => {
    data.push({
      label: city,
      key: index,
      initial: initials[index],
    });
  });
  return data;
};
const data = ref<Option[]>(generateData());
const value1 = ref([]);
const filterMethod = (query, item) => {
  return item.initial.toLowerCase().includes(query.toLowerCase());
};

//步骤栏
const active = ref(0);
const next = () => {
  if (active.value++ > 2) active.value = 0;
};
const prev = () => {
  if (active.value-- > 3) active.value = 0;
};

//商品品牌数据
const categoryData = ref([]);
//获取商品品牌
let categoryList = async () => {
  let newData: any = await api.goods.GoodsBrandList({
    pageNum: 1,
    pageSize: 100,
  });
  let data = newData.list.map((el) => {
    return {
      value: el.name,
      label: el.name,
    };
  });
  categoryData.value = data;
  // console.log(data);
};
categoryList();
// do not use same name with ref
//商品属性的操作
// 步骤3 属性类型请求
// let brandlist = [];
// let attrCategoryList = [];
let optionsB1 = ref([]);
let attrCategoryFn = async () => {
  let attrCategoryRes2: any = await api.goods.attrCategory({
    pageNum: 1,
    pageSize: 100,
  });
  // brandlist = attrCategoryRes2.list; //×
  let optionsB2 = attrCategoryRes2.list.map((item) => {
    return {
      //格式处理
      value: item.name,
    };
  });
  optionsB1.value = optionsB2;
};
attrCategoryFn();
// 步骤3 商品规格三个按钮
let refresh = () => {
  ElMessageBox.confirm("刷新列表将导致sku信息重新生成，是否要刷新", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      ElMessage({
        type: "success",
        message: "刷新成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消刷新",
      });
    });
};
let syncPrice = () => {
  ElMessageBox.confirm("将同步第一个sku的价格到所有sku，是否继续", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      ElMessage({
        type: "success",
        message: "确定同步价格",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消同步价格",
      });
    });
};
let syncStock = () => {
  ElMessageBox.confirm("将同步第一个sku的库存到所有sku，是否继续", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      ElMessage({
        type: "success",
        message: "确定同步库存",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消同步库存",
      });
    });
};
//上传图标
let imageUrl = ref("");
let action = ref("http://120.24.64.5:8088/mall-admin/minio/upload");
const fileList = ref<UploadUserFile[]>([]);
const handlesuccess: UploadProps["onSuccess"] = (file) => {
  // console.log(file.data.url);
  imageUrl.value = file.data.url;
};
//商品关联
//步骤4 选择商品关联
//??format页数无法调出
const generateData1 = (): Option[] => {
  const data1: Option[] = [];
  // let subjectListRes2 = await api.addProduct.subjectList()
  // console.log('subjectListRes2', subjectListRes2)
  // const states1 = [...subjectListRes2.title]

  const states1 = [
    "polo衬衫的也时尚",
    "大牌手机低价秒",
    "晓龙845新品上市",
    "夏天应该穿什么",
    "夏季精选",
    "品牌手机降价",
  ];
  const initials = ["CA", "IL", "MD", "TX", "FL", "CO", "CT"];
  states1.forEach((city, index) => {
    data1.push({
      label: city,
      key: index,
      initial: initials[index],
    });
  });
  return data1;
};
const generateData2 = (): Option[] => {
  const data2: Option[] = [];
  const states2 = ["让音质更出众", "让音质更出众22", "让音质更出众33", "让音质更出众44"];
  const initials = ["CA", "IL", "MD", "TX", "FL", "CO", "CT"];
  states2.forEach((city, index) => {
    data2.push({
      label: city,
      key: index,
      initial: initials[index],
    });
  });
  return data2;
};
const data1 = ref(generateData1());
const data2 = ref(generateData2());
const rightValue = ref([]);
const leftValue = ref([]);
const handleChange = (
  value: number | string,
  direction: "left" | "right",
  movedKeys: string[] | number[]
) => {
  // console.log(value, direction, movedKeys);
};

//富文本
const quillRef = ref();
// watch(quillRef, async (val) => {
//     const quillInstance = val.quillInstance;
//     quillInstance.enable(!props.disabledEdit);
//     quillInstance.on('text-change', () => {
//         // get html content
//         const content = quillInstance.container.firstChild.innerHTML;
//         console.log('quill content: ', content);
//     });
//     // set html content
//     quillInstance.container.firstChild.innerHTML = temp;
// });
// const doUpload = async (formData: any) => {
//     try {
//         // request is axios instance
//         const res = await request(API.uploadImage, formData, {
//             method: 'post',
//             headers: {
//                 'Content-Type': 'multipart/form-data',
//             },
//         });
//         return res.url;
//     } catch (e) {
//         console.log(e);
//     }
// };
//商品分类数据
const withChildrenList = ref([]);
//获取分类数据
let getGoodswithChildrenList = async () => {
  let withdata: any = await api.goods.GoodswithChildrenList();
  let newData = withdata.map((el) => {
    let children = el.children.map((ell) => {
      return {
        value: ell.name,
        label: ell.name,
      };
    });
    return {
      value: el.name,
      label: el.name,
      children: children,
    };
  });
  withChildrenList.value = newData;
  // console.log("newData", newData);
};
getGoodswithChildrenList();
//表单信息提交
const submit = async (formEl: FormInstance | undefined) => {
  ElMessageBox.confirm("是否提交数据? ", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      //添加
      let row2 = {
        brandId: Number(ruleForm.brandId),
        productCategoryId: Number(ruleForm.productCategoryId),
        sort: Number(ruleForm.sort),
        weight: Number(ruleForm.weight),
        stock: Number(ruleForm.stock),
        price: Number(ruleForm.price),
        // name: "",
        name: ruleForm.name,
        albumPics: "",
        brandName: ruleForm.brandName,
        deleteStatus: 0,
        description: "",
        detailDesc: "",
        detailHtml: "",
        detailMobileHtml: "",
        detailTitle: "",
        feightTemplateId: 0,
        flashPromotionCount: 0,
        flashPromotionId: 0,
        flashPromotionPrice: 0,
        flashPromotionSort: 0,
        giftPoint: 0,
        giftGrowth: 0,
        keywords: "",
        lowStock: 0,
        newStatus: 0,
        note: "",
        originalPrice: 0,
        pic: imageUrl.value,
        memberPriceList: [
          {
            memberLevelId: 1,
            memberLevelName: "黄金会员",
          },
          {
            memberLevelId: 2,
            memberLevelName: "白金会员",
          },
          {
            memberLevelId: 3,
            memberLevelName: "钻石会员",
          },
        ],
        productFullReductionList: [
          {
            fullPrice: 0,
            reducePrice: 0,
          },
        ],
        productLadderList: [
          {
            count: 0,
            discount: 0,
            price: 0,
          },
        ],
        previewStatus: 0,
        // price: 0,
        productAttributeCategoryId: null,
        productAttributeValueList: [],
        skuStockList: [],
        subjectProductRelationList: [],
        prefrenceAreaProductRelationList: [],
        // productCategoryId: 197,
        productCategoryName: "11111",
        productSn: "",
        promotionEndTime: "",
        promotionPerLimit: 0,
        promotionPrice: null,
        promotionStartTime: "",
        promotionType: 0,
        publishStatus: 0,
        recommandStatus: 0,
        sale: 0,
        serviceIds: "",
        subTitle: "",
        unit: "",
        usePointLimit: 0,
        verifyStatus: 0,
      };
      let productCreateData = await api.goods.productCreate(row2);
      // console.log(productCreateData);
      // tableData[createData].push(createData)
      ElMessage({
        type: "success",
        message: "提交成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消提交",
      });
    });
};
</script>

<style lang="scss" scoped>
.addgoods {
  width: 800px;
  height: 835px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  overflow: auto;
  color: #303133;
  margin: 0 auto;
  margin-top: 30px;
  padding: 35px;
  box-sizing: border-box;
  .btns {
    width: 100%;
    text-align: center;
  }
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.Bread {
  position: sticky;
  top: -100px;
  margin: 0;
  width: 100%;
  border-bottom: 1px solid #eee;
  // box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, 0.2);
  padding-left: 20px;
  box-sizing: border-box;
}
</style>
